<template>
  <div class="wps-page">
    <!-- 顶部标题区域 -->
    <div class="page-header mb-6">
      <h2 class="title">焊接WPS管理</h2>
      <p class="desc">管理焊接工艺规程（WPS）文档，支持版本管理和状态控制</p>
    </div>

    <!-- 搜索与操作区 -->
    <el-card class="search-card mb-6">
      <div class="search-container">
        <el-row :gutter="20">
          <!-- 搜索与筛选 -->
          <el-col :span="18">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="搜索WPS编号或名称"
                  prefix-icon="el-icon-search"
                  clearable
                ></el-input>
              </el-col>
              <!-- <el-col :span="5">
                <el-select
                  v-model="searchForm.category"
                  placeholder="所有分类"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in categoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-col> -->
              <el-col :span="5">
                <el-select
                  v-model="searchForm.status"
                  placeholder="所有状态"
                  clearable
                >
                  <el-option label="启用" value="active"></el-option>
                  <el-option label="禁用" value="inactive"></el-option>
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-button 
                  type="primary" 
                  @click="handleSearch"
                >
                  搜索
                </el-button>
                <el-button 
                  @click="handleReset"
                >
                  重置
                </el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- WPS列表 -->
    <el-card>
      <div class="table-header">
        <el-button 
          type="primary" 
          icon="el-icon-plus"
          @click="openWpsModal()"
          size="medium"
        >
          添加WPS文档
        </el-button>
      </div>
      <el-table
        :data="wpsList"
        v-loading="loading"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <!-- 序号列 -->
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        ></el-table-column>

        <!-- 名称列 -->
        <el-table-column
          prop="name"
          label="名称"
          min-width="200"
        ></el-table-column>

        <!-- 分类列 -->
        <!-- <el-table-column
          prop="category"
          label="分类"
          min-width="120"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.category?.name || scope.row.category_name || '-' }}</span>
          </template>
        </el-table-column> -->

        <!-- 状态列 -->
        <el-table-column
          label="状态"
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :class="['wps-status-tag', `wps-status-${scope.row.status}`]"
              size="small"
            >
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 上传时间列 -->
        <el-table-column
          prop="uploadTime"
          label="上传时间"
          min-width="140"
        >
          <template slot-scope="scope">
            {{ scope.row.uploadTime | formatDate }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          min-width="200"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="openViewModal(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="openWpsModal(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              :style="{ color: scope.row.status === 'active' ? '#F53F3F' : '#00B42A' }"
              @click="handleDisable(scope.row)"
            >
              {{ scope.row.status === 'active' ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑WPS抽屉 -->
    <el-drawer
      :title="modalTitle"
      :visible.sync="wpsModalVisible"
      direction="rtl"
      :size="700"
      :close-on-click-modal="false"
      class="wps-drawer"
    >
      <div style="padding: 20px;">
        <el-form
          ref="wpsForm"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="modal-form"
        >
          <el-row :gutter="24">
            <!-- 分类 -->
            <!-- <el-col :span="24">
              <el-form-item label="分类" prop="category_id">
                <el-select 
                  v-model="formData.category_id"
                  placeholder="请选择分类"
                  style="width: 100%;"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in categoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->

            <!-- 状态 -->
            <el-col :span="24">
              <el-form-item label="状态">
                <el-select 
                  v-model="formData.status"
                  style="width: 100%;"
                >
                  <el-option label="启用" :value="1"></el-option>
                  <el-option label="禁用" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 文档名称 -->
            <el-col :span="24">
              <el-form-item label="文档名称" prop="name">
                <el-input 
                  v-model="formData.name" 
                  placeholder="请输入WPS文档名称"
                  maxlength="100"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>

            <!-- WPS文件上传 -->
            <el-col :span="24">
              <el-form-item label="WPS文档" prop="files">
                <el-upload
                  class="upload-demo"
                  action=""
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  :on-remove="handleFileRemove"
                  accept=".pdf"
                  :file-list="fileList"
                  multiple
                >
                  <el-button size="medium" type="primary" icon="el-icon-upload">
                    选择PDF文件（可多选）
                  </el-button>
                  <div slot="tip" class="el-upload__tip">
                    支持格式：PDF，可同时上传多个文件，单个文件不超过20MB
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>

            <!-- 描述 -->
            <el-col :span="24">
              <el-form-item label="描述">
                <el-input 
                  v-model="formData.description" 
                  type="textarea" 
                  rows="4"
                  placeholder="请输入WPS文档描述（可选）"
                  maxlength="300"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div style="text-align: right; margin-top: 30px; padding-top: 20px; border-top: 1px solid #EBEEF5;">
          <el-button @click="wpsModalVisible = false" size="medium">取消</el-button>
          <el-button type="primary" @click="saveWps" size="medium">
            {{ modalTitle.includes('编辑') ? '保存修改' : '创建' }}
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 查看WPS模态框 -->
    <el-dialog
      :title="viewTitle"
      :visible.sync="viewModalVisible"
      width="900px"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :body-style="{ padding: 0 }"
    >
      <div class="view-wps-container">
        <!-- 内容区域（左右分栏） -->
        <div class="view-content">
          <!-- 左侧预览区 -->
          <div class="preview-area">
            <div class="preview-placeholder" v-if="currentWps.file_url && currentWps.file_url.length > 0">
              <iframe 
                :src="currentWps.file_url[currentPageIndex]" 
                class="preview-pdf"
                frameborder="0"
              ></iframe>
              <div class="page-control" v-if="currentWps.file_url.length > 1">
                <span class="page-info">第{{ currentPageIndex + 1 }}个文件 / 共{{ currentWps.file_url.length }}个文件</span>
                <div class="page-btn-group">
                  <el-button
                    size="mini"
                    icon="el-icon-arrow-left"
                    :disabled="currentPageIndex === 0"
                    @click="prevPage"
                  ></el-button>
                  <el-button
                    size="mini"
                    icon="el-icon-arrow-right"
                    :disabled="currentPageIndex >= currentWps.file_url.length - 1"
                    @click="nextPage"
                  ></el-button>
                </div>
              </div>
            </div>
            <div class="preview-placeholder" v-else>
              <div style="text-align: center; padding: 100px 0; color: #999;">
                <i class="el-icon-document" style="font-size: 64px;"></i>
                <p style="margin-top: 20px;">暂无预览内容</p>
              </div>
            </div>
          </div>

          <!-- 右侧信息栏 -->
          <div class="info-sidebar">
            <div class="info-title">文档信息</div>
            <div class="info-list">
              <div class="info-item">
                <div class="info-label">文档名称</div>
                <div class="info-value">{{ currentWps.name }}</div>
              </div>
              <div class="info-item">
                <div class="info-label">状态</div>
                <div class="info-value">
                  <el-tag
                    :class="`wps-status-${currentWps.status}`"
                    size="mini"
                  >
                    {{ currentWps.status === 'active' ? '启用' : '禁用' }}
                  </el-tag>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">上传时间</div>
                <div class="info-value">{{ currentWps.uploadTime | formatDate }}</div>
              </div>
              <div class="info-item">
                <div class="info-label">描述</div>
                <div class="info-value">{{ currentWps.description || '无' }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api';
import axios from 'axios';

export default {
  data() {
    return {
      // 搜索表单
      searchForm: {
        keyword: '',
        category: '',
        status: ''
      },

      // WPS列表数据
      wpsList: [],

      // 分类列表
      categoryList: [],

      // 分页配置
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },

      // 加载状态
      loading: false,

      // 模态框状态
      wpsModalVisible: false,
      viewModalVisible: false,
      modalTitle: '添加WPS文档',
      viewTitle: '查看WPS文档',

      // 表单数据
      formData: {
        id: '',
        name: '',
        category_id: '',
        description: '',
        status: 1, // 默认启用 (1=启用, 0=禁用)
        files: [],
        file_url: [] // 文件URL数组
      },

      // 文件上传列表
      fileList: [],

      // 当前查看的WPS数据
      currentWps: {},

      // 当前预览页码索引
      currentPageIndex: 0,

      // 基础URL（用于文件预览）
      // baseURL: process.env.VUE_APP_BASE_URL || '',

      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入文档名称', trigger: 'blur' },
          { min: 5, max: 100, message: '名称长度在5-100个字符之间', trigger: 'blur' }
        ],
        files: [
          { 
            validator: (rule, value, callback) => {
              // 新增时必须上传文件，编辑时可不上传（保留原有文件）
              if (!this.formData.id && this.formData.file_url.length === 0) {
                callback(new Error('请至少上传一个WPS文档'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      }
    };
  },
  mounted() {
    this.getWpsList();
    // this.getCategories();
    
  },
  methods: {
    // 获取WPS列表
    async getWpsList() {
      try {
        this.loading = true;
        const params = {
          title: this.searchForm.keyword || undefined,
          category_id: this.searchForm.category || undefined,
          status: this.searchForm.status ? (this.searchForm.status === 'active' ? 1 : 0) : undefined,
          page: this.pagination.page,
          page_size: this.pagination.size
        };
        
        const res = await api.wps.getWpsList(params);
        
        if (res && res.code === 200) {
          const data = res.data;
          this.wpsList = (Array.isArray(data.list) ? data.list : (Array.isArray(data) ? data : [])).map(item => {
            // 解析 file_url (可能是JSON字符串)
            let fileUrls = [];
            if (item.file_url) {
              try {
                fileUrls = typeof item.file_url === 'string' ? JSON.parse(item.file_url) : item.file_url;
              } catch (e) {
                fileUrls = [];
              }
            }
            
            return {
              id: item.id,
              number: item.number || item.code || '',
              name: item.title || item.name || '',
              category: item.category || null,
              category_name: item.category?.name || item.category_name || '',
              category_id: item.category_id || '',
              status: item.status === 1 ? 'active' : 'inactive',
              uploadTime: item.created_at || item.upload_time || '',
              description: item.remark || '',
              file_url: fileUrls
            };
          });
          this.pagination.total = data.total || this.wpsList.length;
        }
      } catch (error) {
        this.$message.error('获取WPS列表失败');
      } finally {
        this.loading = false;
      }
    },

    // 获取分类列表
    async getCategories() {
      try {
        const res = await api.wps.getWpsCategories({});
        if (res && res.code === 200) {
          const data = res.data;
          this.categoryList = Array.isArray(data.list) ? data.list : (Array.isArray(data) ? data : []);
        }
      } catch (error) {
      }
    },

    // 搜索功能
    handleSearch() {
      this.pagination.page = 1;
      this.getWpsList();
    },

    // 重置功能
    handleReset() {
      this.searchForm = {
        keyword: '',
        category: '',
        status: ''
      };
      this.pagination.page = 1;
      this.getWpsList();
    },

    // 打开新增/编辑模态框
    openWpsModal(row) {
      if (row) {
        // 编辑模式
        this.modalTitle = '编辑WPS文档';
        
        // 解析 file_url
        let fileUrls = [];
        if (row.file_url) {
          try {
            fileUrls = typeof row.file_url === 'string' ? JSON.parse(row.file_url) : row.file_url;
          } catch (e) {
            fileUrls = Array.isArray(row.file_url) ? row.file_url : [];
          }
        }
        
        this.formData = {
          id: row.id || '',
          name: row.name || '',
          category_id: row.category_id || '',
          description: row.description || '',
          status: row.status === 'active' ? 1 : 0,
          files: [],
          file_url: fileUrls
        };
        
        // 如果有已上传的文件，显示在文件列表中（用于回显）
        this.fileList = fileUrls.map((url, index) => {
          // 从URL中提取文件名
          const fileName = url.split('/').pop() || `文件${index + 1}.pdf`;
          
          return {
            name: fileName,
            url: url,
            uid: Date.now() + index,
            status: 'success'
          };
        });
      } else {
        // 新增模式
        this.modalTitle = '添加WPS文档';
        this.formData = {
          id: '',
          name: '',
          category_id: '',
          description: '',
          status: 1, // 默认启用
          files: [],
          file_url: []
        };
        this.fileList = [];
      }
      
      this.wpsModalVisible = true;
      
      // 在下一帧清除验证
      this.$nextTick(() => {
        this.$refs.wpsForm && this.$refs.wpsForm.clearValidate();
      });
    },

    // 打开查看模态框
    openViewModal(row) {
      // 解析 file_url
      let fileUrls = [];
      if (row.file_url) {
        try {
          fileUrls = typeof row.file_url === 'string' ? JSON.parse(row.file_url) : row.file_url;
        } catch (e) {
          fileUrls = Array.isArray(row.file_url) ? row.file_url : [];
        }
      }
      
      this.currentWps = { 
        ...row,
        file_url: fileUrls
      };
      this.currentPageIndex = 0; // 重置页码
      this.viewModalVisible = true;
    },

    // 上一页
    prevPage() {
      if (this.currentPageIndex > 0) {
        this.currentPageIndex--;
      }
    },

    // 下一页
    nextPage() {
      if (this.currentWps.file_url && this.currentPageIndex < this.currentWps.file_url.length - 1) {
        this.currentPageIndex++;
      }
    },

    // 文件上传变化 - 选择时立即上传
    async handleFileChange(file, fileList) {
      // 验证文件大小
      const maxSize = 20 * 1024 * 1024; // 20MB
      if (file.size > maxSize) {
        this.$message.error(`文件 ${file.name} 大小超过20MB限制`);
        // 移除超大文件
        const index = fileList.indexOf(file);
        if (index > -1) {
          fileList.splice(index, 1);
        }
        return;
      }
      
      // 立即上传新添加的文件
      if (file.raw) {
        try {
          // 设置文件上传中状态
          file.status = 'uploading';
          this.$set(file, 'percentage', 0);
          
          const uploadFormData = new FormData();
          uploadFormData.append('files[]', file.raw); // 修改为 files[] 数组格式
          
          const uploadRes = await api.wps.uploadWpsFiles(uploadFormData);
          
          if (uploadRes && uploadRes.code === 200) {
            // 获取上传后的文件URL
            const uploadedUrls = Array.isArray(uploadRes.data) ? uploadRes.data : 
                               (uploadRes.data.urls || uploadRes.data.file_urls || []);
            
            if (uploadedUrls.length > 0) {
              // 将上传成功的URL添加到formData
              this.formData.file_url.push(uploadedUrls[0]);
              
              // 设置文件上传成功状态
              file.status = 'success';
              file.url = uploadedUrls[0]; // 保存文件URL
              this.$message.success(`文件 ${file.name} 上传成功`);
            } else {
              throw new Error('未返回文件URL');
            }
          } else {
            throw new Error(uploadRes.message || '上传失败');
          }
        } catch (error) {
          this.$message.error(`文件 ${file.name} 上传失败: ${error.message}`);
          
          // 移除上传失败的文件
          const index = fileList.indexOf(file);
          if (index > -1) {
            fileList.splice(index, 1);
          }
          file.status = 'fail';
        }
      }
      
      this.fileList = fileList;
      
      // 触发表单验证
      this.$refs.wpsForm && this.$refs.wpsForm.validateField('files');
    },

    // 文件移除
    handleFileRemove(file, fileList) {
      // 从file_url数组中移除对应的URL
      if (file.url) {
        const urlIndex = this.formData.file_url.indexOf(file.url);
        if (urlIndex > -1) {
          this.formData.file_url.splice(urlIndex, 1);
        }
      }
      
      this.fileList = fileList;
      
      // 触发表单验证
      this.$refs.wpsForm && this.$refs.wpsForm.validateField('files');
    },

    // 保存WPS文档
    async saveWps() {
      this.$refs.wpsForm.validate(async valid => {
        if (valid) {
          try {
            // 文件已经在选择时上传,直接使用file_url
            const submitData = {
              title: this.formData.name,
              category_id: this.formData.category_id || undefined,
              file_url: this.formData.file_url,
              status: this.formData.status,
              remark: this.formData.description || '' // 提交描述字段为remark
            };
            
            if (this.formData.id) {
              // 编辑模式
              submitData.id = this.formData.id;
              await api.wps.updateWps(submitData);
              this.$message.success('编辑WPS文档成功');
            } else {
              // 新增模式
              await api.wps.createWps(submitData);
              this.$message.success('新增WPS文档成功');
            }
            
            this.wpsModalVisible = false;
            this.getWpsList(); // 刷新列表
            
          } catch (error) {
            this.$message.error(error.message || '保存WPS文档失败');
          }
        }
      });
    },

    // 停用/启用WPS
    async handleDisable(row) {
      const updateStatusName = row.status === 'active' ? '停用' : '启用';
      
      try {
        await this.$confirm(`确定要${updateStatusName}《${row.name}》吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await api.wps.updateWps({
          ...row,
          ...{
            status: row.status === 'active' ? 0 : 1,
            title: row.name,
            file_url: row.file_url || []
          }
        });
        
        this.$message.success(`${updateStatusName}成功`);
        this.getWpsList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(`${updateStatusName}失败`);
        }
      }
    },

    // 分页相关方法
    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.page = 1;
      this.getWpsList();
    },
    handleCurrentChange(page) {
      this.pagination.page = page;
      this.getWpsList();
    }
  }
};
</script>

<style scoped>
/* 页面标题 */
.page-header {
  margin-bottom: 20px;
  text-align: left;
}
.title {
  font-size: 20px;
  font-weight: bold;
  color: #304156;
  margin-bottom: 5px;
  margin-left: 0;
}
.desc {
  color: #86909C;
  font-size: 14px;
  text-align: left;
}

/* 搜索区 */
.search-card {
  padding: 15px 20px;
}
.search-container {
  width: 100%;
}

/* 表格头部 */
.table-header {
  margin-bottom: 16px;
  text-align: left;
}

/* WPS列表样式 */
.wps-number {
  color: #165DFF;
  font-weight: 500;
}
.wps-status-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}
.wps-status-active {
  background-color: #D1FAE5;
  color: #059669;
  border-color: #D1FAE5;
}
.wps-status-inactive {
  background-color: #F3F4F6;
  color: #6B7280;
  border-color: #F3F4F6;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 抽屉表单样式 */
.wps-drawer {
  --drawer-padding: 20px;
}
.modal-form {
  margin-top: 10px;
}

/* 表单提示框 */
.form-hint-box {
  background-color: #F7F8FA;
  border: 1px solid #E5E6EB;
  border-radius: 6px;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4E5969;
  font-size: 13px;
  line-height: 1.5;
  margin-bottom: 16px;
}
.form-hint-box i {
  color: #165DFF;
  font-size: 16px;
}

/* 上传组件样式 */
.upload-demo {
  width: 100%;
}

/* 查看WPS模态框样式 */
.view-wps-container {
  width: 100%;
  /* height: 600px; */
  display: flex;
  flex-direction: column;
}
.view-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #F2F3F5;
  background-color: #F9FAFB;
}
.view-title {
  font-size: 16px;
  font-weight: 500;
  color: #304156;
}
.view-content {
  flex: 1;
  display: flex;
}
.preview-area {
  flex: 3;
  padding: 20px;
  background-color: #F5F7FA;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.preview-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.preview-pdf {
  width: 100%;
  flex: 1;
  min-height: 500px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  background-color: #fff;
}
.page-control {
  margin-top: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  color: #86909C;
  font-size: 14px;
}
.page-btn-group {
  display: flex;
  gap: 8px;
}
.info-sidebar {
  flex: 1;
  padding: 20px;
  border-left: 1px solid #F2F3F5;
  background-color: #FFFFFF;
  overflow-y: auto;
}
.info-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #304156;
}
.info-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.info-label {
  font-size: 12px;
  color: #86909C;
}
.info-value {
  font-size: 14px;
  color: #304156;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-container .el-row {
    flex-direction: column;
    gap: 10px;
  }
}
</style>